﻿import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class SiteMeshFetcher {

    public String fetchSiteContent(String objectType, String viewType) {
        final String BROWSER_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
        final int RETRY_COUNT = 3;

        //String linkinId = pageContext.getAttribute("linkinId");
        String responseContent = "";
        HttpClient client = new HttpClient();
        PostMethod request = new PostMethod("http://www.kvartal.ua/?action=" + objectType + "&section=result");
        request.addRequestHeader("referer", "http://www.kvartal.ua/index.php?action=" + objectType);
        request.setRequestBody(new NameValuePair[]{
                new NameValuePair("psize", "500"),
                new NameValuePair("sort", "loc_id"),
                new NameValuePair("order", "0"),
                new NameValuePair("viewtype", viewType),
                new NameValuePair("navtype", "link"),
                new NameValuePair("doSubmit", "Find")
        });
        try {
            for (int i = 0; i < RETRY_COUNT; i++) {
                try {
                    request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(RETRY_COUNT, true));
                    request.getParams().setParameter(HttpMethodParams.USER_AGENT, BROWSER_USER_AGENT);
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    client.getHttpConnectionManager().getParams().setSoTimeout(5000); // timeout 5 sec
                    int statusCode = client.executeMethod(request);
                    if (statusCode == HttpStatus.SC_OK) {
                        responseContent = request.getResponseBodyAsString();
//                        responseContent = stream2String(request.getResponseBodyAsStream());
                        break;
                    } else {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            if (request != null) {
                request.releaseConnection();
            }
        }
        //System.out.println(responseContent);
        return responseContent;
    }

    public String stream2String(InputStream stream) {
        int bufSize = 2048;
        char[] buf = new char[2048];
        StringBuffer isContent = new StringBuffer();
        try {
            InputStreamReader reader = new InputStreamReader(stream, "cp1251");
            int rSize = 0;
            while ((rSize = reader.read(buf)) > 0) {
                if (rSize < bufSize) {
                    isContent.append(Arrays.copyOfRange(buf, 0, rSize));
                } else
                    isContent.append(buf);
            }
            return isContent.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}